import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.http import JsonResponse
from rest_framework import status
from Model.models import Subdistrict as S
from Model.modelsView import SubDistrictInfo
from tools.Tools import check_text, getCurrentUser, createHandleLog

logger_info = logging.getLogger('info')
res = dict()


def SubDistrict(request):
    res.clear()
    try:
        if request.method == 'GET':
            return querySubDistrict(request)
        elif request.method == 'POST':
            return createSubDistrict(request)
        elif request.method == 'PUT':
            return modifySubDistrict(request)
        elif request.method == 'DELETE':
            return delSubDistrict(request)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 200
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 获取街道信息
def querySubDistrict(request):
    current = request.GET.get('current')
    pageSize = request.GET.get('pageSize')
    name = request.GET.get('name')
    district_id = request.GET.get('district_id')
    subDistrictInfo = SubDistrictInfo.objects.all()
    if check_text(name):
        subDistrictInfo = subDistrictInfo.objectsfilter(name__contains=name)
    if check_text(district_id):
        subDistrictInfo = subDistrictInfo.filter(district_id=district_id)
    total = subDistrictInfo.count()
    dataJson = list(
        subDistrictInfo.values()[int(pageSize) * int(current) - int(pageSize):int(pageSize) * int(current)])
    res['status'] = 200
    res['data'] = dataJson
    res['total'] = total
    res['message'] = '请求成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 新建街道
@transaction.atomic
def createSubDistrict(request):
    body = json.loads(request.body)
    name = body.get('name')
    district_id = body.get('district_id')
    subDistrict = S.objects.create()
    subDistrict.subdistrict_id = subDistrict.id
    subDistrict.district_id = district_id
    subDistrict.name = name
    createHandleLog('新增街道', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《新增街道》权限 新增内容 {body}')
    subDistrict.save()
    res['status'] = 200
    res['message'] = '新建成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 修改街道
@transaction.atomic
def modifySubDistrict(request):
    body = json.loads(request.body)
    subdistrict_id = body.get('subdistrict_id')
    name = body.get('name')
    district_id = body.get('district_id')
    subDistrict = S.objects.get(subdistrict_id=subdistrict_id)
    subDistrict.name = name
    subDistrict.district_id = district_id
    createHandleLog('修改区域', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改街道》权限 新增内容 {body}')
    subDistrict.save()
    res['status'] = 200
    res['message'] = '修改成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 删除街道
@transaction.atomic
def delSubDistrict(request):
    subdistrict_id = request.GET.get('subdistrict_id')
    subDistrict = S.objects.get(subdistrict_id=subdistrict_id)
    createHandleLog('删除街道', str(getCurrentUser(request)), subDistrict.name)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除街道》权限 删除 {subDistrict.name}')
    subDistrict.delete()
    res['status'] = 200
    res['message'] = '删除成功'
    return JsonResponse(res, status=status.HTTP_200_OK)
